package com.jh3502.helper.function.bluetooth;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.jh3502.helper.R;
import com.jh3502.helper.base.BaseActivity;
import com.jh3502.helper.utils.bluetooth.BluetoothDeviceManager;
import com.vise.baseble.ViseBle;
import com.vise.baseble.callback.scan.IScanCallback;
import com.vise.baseble.callback.scan.ScanCallback;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.baseble.model.BluetoothLeDeviceStore;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author harisucici
 */
public class BlueToothListActivity extends BaseActivity {

    @Nullable
    @BindView(R.id.blue_tooth_list)
    ListView blueToothList;
    @Nullable
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @Nullable
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private boolean isScan = true;
    //设备扫描结果展示适配器
    private BlueToothListAdapter mAdapter;

    @NonNull
    private BluetoothLeDeviceStore bluetoothLeDeviceStore = new BluetoothLeDeviceStore();

    @NonNull
    private List<BluetoothLeDevice> deviceList = new ArrayList<>(2);
    // 扫描回调
    @NonNull
    private ScanCallback periodScanCallback = new ScanCallback(new IScanCallback() {
        @Override
        public void onDeviceFound(final BluetoothLeDevice bluetoothLeDevice) {
            bluetoothLeDeviceStore.addDevice(bluetoothLeDevice);
            runOnUiThread(() -> {
                if (mAdapter != null && bluetoothLeDeviceStore != null) {
                    deviceList.clear();
                    for (BluetoothLeDevice device : bluetoothLeDeviceStore.getDeviceList()) {
                        //eType 1.0 AA001257
                        String name = device.getDevice().getName();
                        Log.e("bluetooth", "name=" + name);
                        if (name != null) {
                            String[] arrays = name.split(" ");
                            if ("eType".equals(arrays[0]) || "Gymate_T".equals(arrays[0])) {
                                deviceList.add(device);
                            }
                        }
                    }

                    mAdapter.setListAll(deviceList);
                }
            });
        }

        @Override
        public void onScanFinish(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
        }

        @Override
        public void onScanTimeout() {
        }

    });

    @Override
    public void responseError(int code, String msg) {

    }

    @Override
    protected int setViewId() {
        return R.layout.activity_blue_tooth_list;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        if (isScan) {
            getMenuInflater().inflate(R.menu.menu_stop, menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_scan, menu);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.action_scan:
                startScan();
                isScan = true;
                supportInvalidateOptionsMenu();
                break;
            case R.id.action_stop:
                mSpeaker.speeking("终止扫描");
                stopScan();
                isScan = false;
                supportInvalidateOptionsMenu();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void initView() {
        toolbar.setTitle("");
        toolbarTitle.setText("E尺列表");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        BluetoothDeviceManager.getInstance().init(this);
        mAdapter = new BlueToothListAdapter(this);
        blueToothList.setAdapter(mAdapter);

        blueToothList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //点击某个扫描到的设备进入设备详细信息界面
                BluetoothLeDevice device = (BluetoothLeDevice) mAdapter.getItem(position);
                if (device == null) {
                    return;
                }
                mJh3502HelperApplication.setExtraDevice(device);
                Intent intent = new Intent();
                setResult(Activity.RESULT_OK, intent);
                onBackPressed();
            }
        });

    }

    @Override
    protected void initData() {
        startScan();
    }

    @Override
    protected void doOnDestroy() {
        stopScan();
        bluetoothLeDeviceStore.clear();
    }

    @Override
    protected void doOnResume() {

    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }

    // 开始扫描
    private void startScan() {
        mSpeaker.speeking("扫描E尺，请确认设备是否开机。");
        if (mAdapter != null) {
            mAdapter.setListAll(new ArrayList<>());
        }
        ViseBle.getInstance().startScan(periodScanCallback);
        invalidateOptionsMenu();
    }

    // 停止扫描
    private void stopScan() {

        ViseBle.getInstance().stopScan(periodScanCallback);
        invalidateOptionsMenu();
    }


}
